<template>
  <div class="tenant-container">
    <div
      v-if="!!tenant"
      class="tenant-title"
    ><a @click="dialogChangeTenantVisible=true">{{ L('CurrentTenant') }}:{{ tenant.name }}</a></div>
    <div
      v-if="!tenant"
      class="tenant-title"
    ><a @click="dialogChangeTenantVisible=true">{{ L('NotSelected') }}</a></div>

    <el-dialog
      :title="L('ChangeTenant')"
      width="30%"
      :visible.sync="dialogChangeTenantVisible"
    >
      <el-input
        v-model="changedTenancyName"
        clearable
        :placeholder="L('TenancyName')"
      />
      <div
        v-if="!changedTenancyName"
        style="margin-top:10px"
      >{{ L('LeaveEmptyToSwitchToHost') }}</div>

      <div slot="footer">
        <el-button @click="dialogChangeTenantVisible = false">{{ L('Cancel') }}</el-button>
        <el-button
          type="primary"
          @click="changeTenant"
        >{{ L('OK') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TenantSwitch',
  data() {
    return {
      dialogChangeTenantVisible: false,
      changedTenancyName: ''
    }
  },
  computed: {
    tenant() {
      return this.$store.state.session.tenant
    }
  },
  watch: {
    dialogChangeTenantVisible(value) {
      if (value) {
        this.changedTenancyName = this.$store.state.session.tenant ? this.$store.state.session.tenant.name : ''
      }
    }
  },
  methods: {
    async changeTenant() {
      if (!this.changedTenancyName) {
        abp.multiTenancy.setTenantIdCookie(undefined)
        location.reload()
        return
      } else {
        const tenant = await this.$store.dispatch({
          type: 'account/isTenantAvailable',
          data: { tenancyName: this.changedTenancyName }
        })
        switch (tenant.state) {
          case 1:
            abp.multiTenancy.setTenantIdCookie(tenant.tenantId)
            location.reload()
            return
          case 2:
            this.$message.error(this.L('TenantIsNotActive'))
            break
          case 3:
            this.$message.error(this.L('ThereIsNoTenantDefinedWithName{0}',
              undefined,
              this.changedTenancyName))
            break
        }
      }
    }
  }
}
</script>

<style lang="scss">
.login-container {
  .tenant-container {
    .el-input {
      input {
        color: #000;
        border: 1px solid #dcdfe6;
        caret-color: #000;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.tenant-container {
  color: #fff;
  text-align: center;
}
.tenant-title {
  margin-bottom: 24px;
  text-align: center;
}
</style>

